package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.cluster.routing.Exchange;
import com.aiwiown.snackmq.common.dto.console.ExchangeInfoDTO;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageStatus;
import com.aiwiown.snackmq.common.message.MessageType;
import com.aiwiown.snackmq.common.serialization.JsonSerializer;
import com.aiwiown.snackmq.common.serialization.SerializerFactory;
import lombok.extern.slf4j.Slf4j;

/**
 * 【新增】处理控制台列出所有 Exchange 请求的处理器。
 * 此处理器的缺失是导致 Exchange 页面加载超时的根本原因。
 */
@Slf4j
public class ListExchangesHandler extends AbstractLeaderRequiredConsoleHandler {

    private final JsonSerializer serializer = SerializerFactory.getJsonSerializer();

    public ListExchangesHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.LIST_EXCHANGES_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            java.util.List<Exchange> exchanges = metadataManager.getAllExchanges();
            java.util.List<ExchangeInfoDTO> exchangeDTOs = exchanges.stream()
                    .map(exchange -> {
                        java.util.List<ExchangeInfoDTO.BindingInfoDTO> bindingDTOs = exchange.getBindings().stream()
                                .map(binding -> new ExchangeInfoDTO.BindingInfoDTO(binding.getQueueName(), binding.getRoutingKey()))
                                .collect(java.util.stream.Collectors.toList());
                        return new ExchangeInfoDTO(exchange.getName(), exchange.getType(), bindingDTOs);
                    })
                    .collect(java.util.stream.Collectors.toList());
            byte[] body = serializer.serialize(exchangeDTOs);
            ctx.writeResponse(Message.builder().type(MessageType.RESPONSE).messageId(request.getMessageId()).status(MessageStatus.SUCCESS).body(body).build());
        } catch (Exception e) {
            log.error("Error processing list exchanges request", e);
            ctx.writeResponse(Message.builder().type(MessageType.RESPONSE).messageId(request.getMessageId()).status(MessageStatus.FAILED).errorMessage("Internal server error: " + e.getMessage()).build());
        }
    }
}